package main

import (
	"crypto/tls"
	"crypto/x509"
	"fmt"
	"io"
	"log"
	"os"
)

func main() {
	// 加载客户端证书和私钥
	//cert, err := tls.LoadX509KeyPair("client-cert.pem", "client-key.pem")
	//cert, err := tls.LoadX509KeyPair("client.crt", "client.key")
	cert, err := tls.LoadX509KeyPair("tls/client.crt.pem", "tls/client.key.pem")
	if err != nil {
		log.Fatalf("加载证书和私钥失败: %v", err)
	}

	// 加载根证书
	caCert, err := os.ReadFile("tls/ca.crt.pem")
	if err != nil {
		log.Fatalf("读取根证书失败: %v", err)
	}
	caCertPool := x509.NewCertPool()
	caCertPool.AppendCertsFromPEM(caCert)

	// 配置TLS
	config := &tls.Config{
		Certificates: []tls.Certificate{cert},
		RootCAs:      caCertPool,
	}

	// 连接到服务器
	conn, err := tls.Dial("tcp", "localhost.easyops.local:8443", config)
	if err != nil {
		log.Fatalf("连接到服务器失败: %v", err)
	}
	defer conn.Close()

	// 向服务器发送消息
	message := "Hello, server!"
	_, err = conn.Write([]byte(message))
	if err != nil {
		log.Fatalf("发送消息时出错: %v", err)
	}

	// 从服务器读取响应
	buffer := make([]byte, 1024)
	n, err := conn.Read(buffer)
	if err != nil {
		if err != io.EOF {
			log.Fatalf("读取响应时出错: %v", err)
		}
	}

	// 处理服务器响应
	response := string(buffer[:n])
	fmt.Printf("收到服务器响应: %s\n", response)
}
